What is react-router-dom?
The react-router-dom package is a popular library for handling routing in React web applications. It allows developers to implement dynamic routing in a web app, which is not possible with static routing. With react-router-dom, you can define routes, navigate between them, handle parameters and query strings, and manage the history stack, among other things.
What are react-router-dom's main functionalities?
Basic Routing
This code demonstrates how to set up basic routing in a React application using react-router-dom. It uses the BrowserRouter, Route, and Switch components to define routes for different components in the app.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
</Switch>
</Router>
);
}
Link Navigation
This code snippet shows how to use the Link component to create navigation links that allow users to click through different routes without causing a page reload.
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
<Link to='/contact'>Contact</Link>
</nav>
);
}
Route Parameters
This example demonstrates how to handle dynamic routes using route parameters. The useParams hook is used to access the parameters of the current route.
import { Route, useParams } from 'react-router-dom';
function User() {
let { userId } = useParams();
return <h2>User ID: {userId}</h2>;
}
function Users() {
return (
<Route path='/users/:userId' component={User} />
);
}
Programmatic Navigation
This code shows how to navigate programmatically using the useHistory hook. It allows you to push a new entry onto the history stack, mimicking the behavior of a navigation action.
import { useHistory } from 'react-router-dom';
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push('/home');
}
return (
<button type='button' onClick={handleClick}>
Go home
</button>
);
}
Other packages similar to react-router-dom
reach-router
Reach Router is another routing library for React with a more straightforward, accessible approach compared to react-router-dom. It automatically manages focus for accessibility, and routing is more component-based. However, as of my knowledge cutoff in 2023, Reach Router has been officially merged with React Router, and the team recommends using React Router for new projects.
wouter
Wouter is a minimalist routing library for React and Preact that does not rely on the context API. It offers a simpler API and smaller bundle size compared to react-router-dom, making it a good choice for smaller projects or when you want to keep your project lightweight.
navi
Navi is a JavaScript library for declaratively mapping URLs to asynchronous content. It's designed to work with React and allows for lazy-loading routes, which can help improve performance in large applications. Navi provides a different approach to routing by focusing on content-first routing, which can be beneficial for certain types of applications.
v6.27.0
Date: 2024-10-11
What's Changed
Stabilized APIs
This release stabilizes a handful of "unstable" APIs in preparation for the pending React Router v7 release (see these posts for more info):
unstable_dataStrategy
→ dataStrategy
(createBrowserRouter
and friends) (Docs)unstable_patchRoutesOnNavigation
→ patchRoutesOnNavigation
(createBrowserRouter
and friends) (Docs)unstable_flushSync
→ flushSync
(useSubmit
, fetcher.load
, fetcher.submit
) (Docs)unstable_viewTransition
→ viewTransition
(<Link>
, <Form>
, useNavigate
, useSubmit
) (Docs)
Minor Changes
- Stabilize the
unstable_flushSync
option for navigations and fetchers (#11989) - Stabilize the
unstable_viewTransition
option for navigations and the corresponding unstable_useViewTransitionState
hook (#11989) - Stabilize
unstable_dataStrategy
(#11974) - Stabilize
unstable_patchRoutesOnNavigation
(#11973)
- Add new
PatchRoutesOnNavigationFunctionArgs
type for convenience (#11967)
Patch Changes
- Fix bug when submitting to the current contextual route (parent route with an index child) when an
?index
param already exists from a prior submission (#12003) - Fix
useFormAction
bug - when removing ?index
param it would not keep other non-Remix index
params (#12003) - Fix bug with fetchers not persisting
preventScrollReset
through redirects during concurrent fetches (#11999) - Avoid unnecessary
console.error
on fetcher abort due to back-to-back revalidation calls (#12050) - Fix bugs with
partialHydration
when hydrating with errors (#12070) - Remove internal cache to fix issues with interrupted
patchRoutesOnNavigation
calls (#12055)
- ⚠️ This may be a breaking change if you were relying on this behavior in the
unstable_
API - We used to cache in-progress calls to
patchRoutesOnNavigation
internally so that multiple navigations with the same start/end would only execute the function once and use the same promise - However, this approach was at odds with
patch
short circuiting if a navigation was interrupted (and the request.signal
aborted) since the first invocation's patch
would no-op - This cache also made some assumptions as to what a valid cache key might be - and is oblivious to any other application-state changes that may have occurred
- So, the cache has been removed because in most cases, repeated calls to something like
import()
for async routes will already be cached automatically - and if not it's easy enough for users to implement this cache in userland
- Remove internal
discoveredRoutes
FIFO queue from unstable_patchRoutesOnNavigation
(#11977)
- ⚠️ This may be a breaking change if you were relying on this behavior in the
unstable_
API - This was originally implemented as an optimization but it proved to be a bit too limiting
- If you need this optimization you can implement your own cache inside
patchRoutesOnNavigation
- Fix types for
RouteObject
within PatchRoutesOnNavigationFunction
's patch
method so it doesn't expect agnostic route objects passed to patch
(#11967) - Expose errors thrown from
patchRoutesOnNavigation
directly to useRouteError
instead of wrapping them in a 400 ErrorResponse
instance (#12111)
Full Changelog: v6.26.2...v6.27.0